package com.aric.springbootmusic.controller;

import com.aric.springbootmusic.entity.dto.*;
import com.aric.springbootmusic.entity.param.*;
import com.aric.springbootmusic.enums.UserStatus;
import com.aric.springbootmusic.exceptions.NameDuplicationException;
import com.aric.springbootmusic.service.UserService;
import com.aric.springbootmusic.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 用户登陆
     */
    @PostMapping("/login")
    public Result login(@Validated @RequestBody LoginUserParam loginUserParam){
        LoginUserDTO userDTO = LoginUserDTO.builder()
                .username(loginUserParam.getUsername())
                .password(loginUserParam.getPassword())
                .build();
        return userService.login(userDTO);
    }

    /**
     * 退出登陆
     */
    @PreAuthorize("hasAnyAuthority('AuthorityManager','UserManager','MusicManager')")
    @PostMapping("/logout")
    public Result logout(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String id = (String)authentication.getPrincipal();
        return userService.logout(id);
    }

    /**
     * 注销用户
     */
    @PreAuthorize("hasAuthority('DeleteUser')")
    @DeleteMapping("/deleteUser/{id}")
    public Result deleteUser(@PathVariable("id") String id){
        return userService.deleteUser(id);
    }

    /**
     * 添加用户
     */
    @PreAuthorize("hasAuthority('AddUser')")
    @PostMapping("/addUser")
    public Result addUser(@Validated @RequestBody RegisterUserParam userParam) throws NameDuplicationException {
        RegisterUserDTO userDTO = RegisterUserDTO.builder()
                .username(userParam.getUsername())
                .password(userParam.getPassword())
                .nickname(userParam.getNickname())
                .email(userParam.getEmail())
                .phoneNumber(userParam.getPhoneNumber())
                .status(UserStatus.USER_STATUS_OFFLINE)
                .isDelete(0)
                .roleId(userParam.getRoleId())
                .build();
        return userService.register(userDTO);
    }

    /**
     * 更新用户状态
     */
    @PreAuthorize("hasAuthority('UpdateUser')")
    @PutMapping("/updateUserStatus")
    public Result updateUserStatus(@RequestBody @Validated UserStatusParam userStatusParam){
        UserStatusDTO dto = new UserStatusDTO();
        dto.setId(userStatusParam.getId());
        if(userStatusParam.getStatus()==1){
            dto.setStatus(UserStatus.USER_STATUS_OFFLINE);
        }else {
            dto.setStatus(UserStatus.USER_STATUS_ONLINE);
        }
        return userService.updateUserStatus(dto);
    }

    @PreAuthorize("hasAuthority('UpdateUser')")
    @PutMapping("/updateUser")
    public Result updateUser(@RequestBody @Validated EditUserParam editUserParam){
        EditUserDTO userDTO = EditUserDTO.builder()
                .id(editUserParam.getId())
                .nickname(editUserParam.getNickname())
                .phoneNumber(editUserParam.getPhoneNumber())
                .email(editUserParam.getEmail())
                .build();
        return userService.updateUser(userDTO);
    }


    /**
     * 根据用户id查询用户所具有的角色信息
     * @param id 用户id
     * @return
     */
    @PreAuthorize("hasAuthority('UpdateUser')")
    @GetMapping("/selectUserRole/{id}")
    public Result findUserRole(@PathVariable("id") String id){
        return userService.selectUserRoleById(id);
    }

    @PreAuthorize("hasAuthority('UpdateUser')")
    @PutMapping("/updateUserRole")
    public Result updateUserRole(@RequestBody @Validated EditUserRoleParam editUserRoleParam){
        EditUserRoleDTO dto = EditUserRoleDTO.builder()
                .id(editUserRoleParam.getId())
                .roleId(editUserRoleParam.getRoleId())
                .build();
        return userService.modifyUserRole(dto);
    }

    /**
     * 更新密码
     */
    @PreAuthorize("hasAuthority('UpdateUser')")
    @PutMapping("/updateUserPassword")
    public Result updateUserPassword(@RequestBody @Validated UpdateUserPassWordParam updateUserPassWordParam){
        UpdateUserPassWordParamDTO updateUserPassWordParamDTO = UpdateUserPassWordParamDTO.builder()
                .id(updateUserPassWordParam.getId())
                .oldPassword(updateUserPassWordParam.getOldPassword())
                .newPassword(updateUserPassWordParam.getNewPassword())
                .build();
        return userService.updateUserPassword(updateUserPassWordParamDTO);
    }

    /**
     * 查询单个用户
     */
    @PreAuthorize("hasAuthority('SelectUser')")
    @GetMapping("/selectSingleUser/{id}")
    public Result selectSingleUser(@PathVariable("id") String id){
        return userService.findUserById(id);
    }

    /**
     * 查询所有用户
     */
    @PreAuthorize("hasAuthority('UserList')")
    @GetMapping("/selectAllUser")
    public Result selectAllUser(QueryAllUserParam queryAllUserParam){
        QueryAllUserDTO allUserDTO = QueryAllUserDTO.builder()
                                                    .keyword(queryAllUserParam.getKeyword())
                                                    .currentPage(queryAllUserParam.getCurrentPage())
                                                    .pageSize(queryAllUserParam.getPageSize())
                                                    .build();
        return userService.findAllUser(allUserDTO);
    }

    /**
     * 查询用户的基本信息和权限信息
     */
    @PreAuthorize("hasAnyAuthority('AuthorityManager','UserManager','MusicManager')")
    @GetMapping("/selectMenus")
    public Result selectMenus(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String id = (String)authentication.getPrincipal();
        return userService.getMenus(id);
    }
    @PreAuthorize("hasAuthority('UserList')")
    @GetMapping("/findUserAllAuthority")
    public Result selectUserAllAuthority(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String id = (String)authentication.getPrincipal();
        return userService.getAuthoritys(id);
    }
}
